﻿using BaiDuYunAddSpeed.Tool;
using Gma.System.MouseKeyHook;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using static BaiDuYunAddSpeed.Tool.ScreenCoordinates;

namespace BaiDuYunAddSpeed
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private IKeyboardMouseEvents m_GlobalHook;

        [DllImport("gdi32.dll", SetLastError = true)]
        private static extern bool DeleteObject(IntPtr hObject);


        /// <summary>
        /// 从bitmap转换成ImageSource
        /// </summary>
        /// <param name="icon"></param>
        /// <returns></returns>
        public ImageSource ChangeBitmapToImageSource(Bitmap bitmap)
        {
            //Bitmap bitmap = icon.ToBitmap();
            IntPtr hBitmap = bitmap.GetHbitmap();
            ImageSource wpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                hBitmap,
                IntPtr.Zero,
                Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());
            if (!DeleteObject(hBitmap))
            {
                throw new System.ComponentModel.Win32Exception();
            }
            return wpfBitmap;
        }

        public MainWindow()
        {
            InitializeComponent();
            m_GlobalHook = Hook.GlobalEvents();
            //m_GlobalHook.MouseDownExt += GlobalHookMouseDownExt;
            m_GlobalHook.MouseUpExt += M_GlobalHook_MouseUpExt;
            m_GlobalHook.MouseMoveExt += M_GlobalHook_MouseMoveExt;
            //m_GlobalHook.KeyPress += GlobalHookKeyPress;
            DragToObtainPID.Source = ChangeBitmapToImageSource(Resource1.AimedAtPositioning);
            if (!File.Exists("C:\\Windows\\System32\\win32_new.dll"))
            {
                ByteToFile(Resource1.HookDll, "C:\\Windows\\System32\\win32_new.dll");
            }
        }

        [DllImport("user32.dll", EntryPoint = "WindowFromPoint")]//指定坐标处窗体句柄
        public static extern int WindowFromPoint(int xPoint, int yPoint);

        [DllImport("user32", SetLastError = true)]
        private static extern int GetWindowText(
            int hWnd,//窗口句柄
            StringBuilder lpString,//标题
            int nMaxCount //最大值
            );
        int Handle = 0;
        CursorPoint point;
        StringBuilder lpString = new StringBuilder();
        int pid; 
        private void M_GlobalHook_MouseMoveExt(object sender, MouseEventExtArgs e)
        {
            if (Visibility.Collapsed == DragToObtainPID.Visibility)
            {
                point = ScreenCoordinates.GetTheMouseCoordinates();
                int intPtr = WindowFromPoint(point.X, point.Y);
                if (intPtr != Handle)
                {
                    Handle = intPtr;
                    GetWindowText(intPtr, lpString, lpString.MaxCapacity);
                    GetWindowThreadProcessId((IntPtr)Handle, ref pid);
                }
                Information.Content = $"句柄：{intPtr}|进程ID：{pid}\n窗体名称：{lpString}\n鼠标坐标：[X：{point.X}-Y：{point.Y}]";
            }
        }



        private void M_GlobalHook_MouseUpExt(object sender, MouseEventExtArgs e)
        {
            DragToObtainPID.Visibility = Visibility.Visible;
            TheMouseStyle.OnApplicationQuit();
        }

        //private void GlobalHookMouseDownExt(object sender, MouseEventExtArgs e)
        //{
        //    throw new NotImplementedException();
        //}

        public bool ByteToFile(byte[] byteArray, string fileName)
        {
            bool result = false;
            try
            {
                using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    fs.Write(byteArray, 0, byteArray.Length);
                    result = true;
                }
            }
            catch
            {
                result = false;
            }
            return result;
        }


        [DllImport("win32_new.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern int StartHook(UInt32 pid);


        [DllImport("win32_new.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern void setSpeed(Double speed);

        [DllImport("win32_new.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern void StopHook(UInt32 pid);


        [DllImport("user32", EntryPoint = "GetWindowThreadProcessId")]
        private static extern int GetWindowThreadProcessId(IntPtr hwnd, ref int pid);

        private void OpenTheSpeed_Click(object sender, RoutedEventArgs e)
        {
            //List<int> pid = new List<int>();
            //Process[] processes = Process.GetProcesses();
            //foreach (Process process in processes)
            //{
            //    if (process.ProcessName.Contains("baidu"))
            //    {
            //        //Console.WriteLine($"ProcessName = ({process.ProcessName}), Id = {process.Id}");
            //        pid.Add(process.Id) ;
            //    }
            //}

            //foreach (UInt32 item in pid)
            //{
            int pid = 0;
            GetWindowThreadProcessId((IntPtr)Handle, ref pid);
            StopHook(Convert.ToUInt32(pid));
            int a = StartHook(Convert.ToUInt32(pid));
            //MessageBox.Show("初始化");
            if (string.IsNullOrEmpty(AMultiple.Text))
            {
                AMultiple.Text = "500";
            }
            Regex reg = new Regex("^[1-9]\\d*$");
            if (!reg.Match(AMultiple.Text).Success)
            {
                MessageBox.Show("请输入数字");
                return;
            }
            setSpeed(Convert.ToDouble(Convert.ToDouble(AMultiple.Text)));
            //}

        }

        private void ClosingSpeed_Click(object sender, RoutedEventArgs e)
        {
            //List<int> pid = new List<int>();
            //Process[] processes = Process.GetProcesses();
            //foreach (Process process in processes)
            //{
            //    if (process.ProcessName.Contains("baidu"))
            //    {
            //        //Console.WriteLine($"ProcessName = ({process.ProcessName}), Id = {process.Id}");
            //        pid.Add(process.Id);
            //    }
            //}

            //foreach (uint item in pid)
            //{
            int pid = 0;
            GetWindowThreadProcessId((IntPtr)Handle, ref pid);
            StopHook(Convert.ToUInt32(pid));
            //}
        }

        private void DragToObtainPID_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            DragToObtainPID.Visibility = Visibility.Collapsed;
            TheMouseStyle.Change();
        }

        private void DragToObtainPID_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            DragToObtainPID.Visibility = Visibility.Visible;
        }

        private void TheEndOfTheProcess_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                int pid = 0;
                GetWindowThreadProcessId((IntPtr)Handle, ref pid);
                Process[] processes = System.Diagnostics.Process.GetProcesses();
                foreach (Process item in processes)
                {
                    if (item.Id == pid)
                    {
                        item.Kill();
                        break;
                    }
                }
            }
            catch
            {

            }
        }

    }
}
